package gwtappcontainer.server.apis.insight;

import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.insight.Member;
import gwtappcontainer.shared.apis.insight.ProgramTypeProp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Load;

@Entity @Cache
class MemberEntity {
	@Id Long id;
	@Index String email;
	
	@Index String firstName;
	String middleName;
	String lastName;
	
	String homeAddress;
	String homePhone;
	
	String officeAddress;
	String officePhone;
	
	String singaporeNRIC;
	
	@Index @Load Ref<CenterEntity> primaryCenter;
	@Index @Load HashSet<Ref<CenterEntity>> centers = new HashSet<Ref<CenterEntity>>();	
	
	@Index @Load HashSet<Ref<ProgramTypeEntity>> programTypes = 
			new HashSet<Ref<ProgramTypeEntity>>();
	
	@Load Ref<UnlistedProgramsEntity> unlistedPrograms;	
	
	Member toProp() {
		Member prop = new Member();
		prop.id = id;
		prop.email = email;
		prop.firstName = firstName;
		prop.middleName = middleName;
		prop.lastName = lastName;
		prop.homeAddress = homeAddress;
		prop.homePhone = homePhone;
		prop.officeAddress = officeAddress;
		prop.officePhone = officePhone;
		prop.singaporeNRIC = singaporeNRIC;
		prop.primaryCenter = primaryCenter.get().toProp();
		
		for (Ref<CenterEntity> center : centers)
			prop.additionalCenters.add(center.get().toProp());				
					
		Collections.sort(prop.additionalCenters);
		
		if (unlistedPrograms != null) {
			ArrayList<UnlistedProgramsEmbeddedEntity> programs =
					unlistedPrograms.get().programs;
			for (int i = 0; i < programs.size(); i++) {
				prop.unlistedPrograms.add(programs.get(i).toProp());
			}
			
			Collections.sort(prop.unlistedPrograms);
		}
		
		prop.programTypes = new ArrayList<>();
		for (Ref<ProgramTypeEntity> iterable_element : programTypes) {
			if (null == iterable_element)
				throw new APIException(Status.ERROR_UNHANDLED_EXCEPTION, 
						"iterable_element is null");
			ProgramTypeEntity programTypeEntity = iterable_element.get();
			ProgramTypeProp programTypeProp = programTypeEntity.toProp();
			prop.programTypes.add(programTypeProp);
		}
										
		return prop;
	}
}
